export default {
  // indexedDB兼容
  indexedDB: window.indexedDB || window.webkitindexedDB || window.msIndexedDB || mozIndexedDB,
  // 打开数据库
  // 新对象储存空间newStore参数：newStore.name、newStore.key
  // 新增对象存储空间要更改数据库版本
  // @param {object} dbname 数据库名称
  // @param {string} newStoreList 仓库名称
  // @param {string} version 数据库的版本
  // @param {string} callback 成功回调
  openDB: function (dbname, version, newStoreList, callback) {
    console.log('openDB-------------',version)
    var version = version || 1;
    var db
    var request = this.indexedDB.open(dbname, version);
    request.onerror = function (event) {
      console.log(event);
      console.log('IndexedDB数据库打开错误');
    };
    request.onsuccess = function (event) {
      console.log('IndexedDB数据库打开');
      db = event.target.result;
      db.onversionchange = function () {
        console.log('[req] Database is outdated, please reload the page.')
        db.close()

      }
      if (callback && (typeof callback === 'function')) {
        callback(db);
      }
    };
    // onupgradeneeded，调用创建新的储存空间（创建表）
    request.onupgradeneeded = function (event) {
      console.log('onupgradeneeded新建数据库--------------------');
      var db = event.target.result;
      if (newStoreList.length == 0) return
      newStoreList.forEach(item => {
        if (item) {
          console.log('onupgradeneeded新建数据库--------------------'+item.name);
          if ((db.objectstoreNames && !db.objectstoreNames.includes(item.name)) || !db.objectstoreNames) {
            var objectStore = db.createObjectStore(item.name, {
              keyPath: item.key,//主键键值
            });
            console.log(item["index"])
            if (item["index"]&&item["index"].length>0) {
              item["index"].forEach((subItem,index)=>{
                objectStore.createIndex(subItem, subItem, {
                  unique: false
                });
              })
            }
            if(item['multipleIndex']){//多重查询条件索引
              for(let key in item['multipleIndex']){
                objectStore.createIndex(key, item['multipleIndex'][key], {
                  unique: false
                });
              }
            }
          }
        }
      });

    };
  },
  // 删除数据库
  deleteDB: function (dbname, callback) {
    var deleteQuest = this.indexedDB.deleteDatabase(dbname);
    deleteQuest.onerror = function () {
      console.log('删除数据库出错');
    };
    deleteQuest.onsuccess = function () {
      if (callback && (typeof callback === 'function')) {
        callback();
      }
    }
  },
  // 关闭数据库
  closeDB: function (dbname) {
    dbname.close();
  },
  addDatas: function (db, storeName, datas, callback) {
    console.log('数据库底层添加数据',storeName)
    this.getdatabycursor(db, storeName).then(arr => {
      var store = db.transaction(storeName, 'readwrite').objectStore(storeName),
        request;
      for (let i = 0, len = datas.length; i < len; i++) {
        request = store.put(datas[i]);
        request.onerror = function () {
          console.error('PUT添加数据报错');
          callback({code:"200",err:'数据添加失败'});
        };
        request.onsuccess = function (result) {
          if (callback && (typeof callback === 'function')&&i==datas.length-1) {
            console.log('PUT添加数据成功');
            callback({code:"500",message:"数据添加成功"});
          }
        };
      }
    })
  },
  updateData: function (db, storeName, key, updateObj, callback) {
    return new Promise((resolve, reject) => {
    this.getDataBykey(db, storeName, key).then(
      (data) => {
        const d = data;
        for(let key in updateObj){
          d[key]=updateObj[key]
        }
        let objectStore=db.transaction(storeName, 'readwrite').objectStore(storeName)
        const objectStoreUpdate = objectStore.put(d);
          objectStoreUpdate.onsuccess = function (e) {
            console.log('update success')
            resolve('success')
          }
        })
      }
    )
  },
  // 删除数据
  // 数据库名,表名,主键
  deleteData: function (db, storename, key) {
    var store = db.transaction(storename, 'readwrite').objectStore(storename);
    store.delete(key);
    var request = store.delete(key);
    return new Promise((resolve, reject) => {
      request.onsuccess = function (e) {
        console.log('数据删除成功')
        resolve('success')
      }
    })
  },
  // @param {object} deleteObject  删除条件对象{key1:value1,key2:value2}
  // @param {string} key 被删除数据的主键名称
  deleteDataByCounter:function(db,storeName,deleteObject, key){
    var store =  db.transaction(storeName, 'readwrite').objectStore(storeName);
    const request = store.openCursor();
    console.log("操作表名：" + storeName);
    console.log("操作参数：" , deleteObject);
    console.log("操作主键：" + key);
    return new Promise((resolve, reject) => {
      request.onsuccess=(event)=>{
        const cursor=event.target.result;
        if(cursor){
          let deleteFlag=Object.entries(deleteObject).every((el,index)=>{
            return cursor.value[el[0]]===el[1]
          })
          console.log("删除标识deleteFlag :" + deleteFlag);
          if(deleteFlag){
            console.log("执行删除：" + cursor.value[key]);
            cursor.delete(cursor.value[key])
          }
          cursor.continue()
        }else{
          console.log('删除结束');
          resolve(true);
        }
      }
    })
   
  },
  // //通过游标遍历数据
  getdatabycursor: function (db, storeName) {
    var objectStore = db.transaction(storeName).objectStore(storeName);
    var dataList = [];
    var i = 0;
    return new Promise((resolve, reject) => {
      objectStore.openCursor().onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
          dataList.push(cursor.value)
          cursor.continue();
        } else {
          resolve(dataList);
        }

      };
    })

  },
  //根据counter索引模糊查询数据
  getdatabyCounter: function (db, storeName, indexName, values) {
    console.log('getdatabyCounter',indexName,values)
    var transaction = db.transaction(storeName);
    var store = transaction.objectStore(storeName);
    var indexs = store.index(indexName);
    var datas = [];
    var request =this.onlyOrBound(indexs,values)
    return new Promise((resolve, reject) => {
      request.onsuccess = function (e) {
        var cursor = e.target.result;
        if (cursor) {
          datas.push(cursor.value);
          cursor.continue();
        } else {
          resolve(datas)
        }
      }
    })
  },
  getdata: function (db, storeName) {
    var objectStore = db.transaction(storeName).objectStore(storeName);
    console.log('objectStore='+objectStore)
    var data = [];
    return new Promise((resolve, reject) => {

      objectStore.openCursor().onsuccess = function (event) {
        var cursor = event.target.result;
        if (cursor) {
          data.push(cursor.value)
          cursor.continue();
        } else {
          resolve(data)
        }
      };
    })
  },
  //根据key查询数据
  getDataBykey: function (db, storeName, key) {
    console.log('getDataBykey',key)
    var transaction = db.transaction(storeName);
    var objectStore = transaction.objectStore(storeName);
    var request = objectStore.get(key);
    request.onerror = function (event) {};
    return new Promise((resolve, reject) => {
      request.onsuccess = function (event) {
        console.log('getDataBykey',request)
        if (request.result) {
          resolve(request.result);
        } else {
          resolve(false);
        }
      };
    })
  },
  onlyOrBound(indexs,values){
    let isArray=Array.isArray(values);
    if(isArray&&values.length>0){
      return indexs.openCursor(IDBKeyRange.only(values))
    }
    return indexs.openCursor(IDBKeyRange.bound(values,values+'￥',false,false))
  }
}
